<template>
  <div id="article-list" ref="articleRef">
    <Loading v-if="!articles.length" />
    <h2 class="title" ref="titleRef">博客文章列表</h2>
    <div class="items">
      <ul ref="ulRef" class="card">
        <li class="article-item" v-for="item of articles" :key="item._id">
          <img class="coverImg" :src="item.coverImg" alt="" />
          <div class="backdrop"></div>
          <div class="text">
            <h3 class="article-title">{{ item.title }}</h3>
            <p class="article-introduction">{{ item.introduction }}</p>
            <div class="line"></div>
            <div class="article-inf">
              <i class="iconfont icon-pinglun1-copy"
                ><span>{{ item.commentNum }}条评论</span></i
              >
              <i class="iconfont icon-xihuan"
                ><span>{{ item.voteNum }}人点赞</span></i
              >
              <i class="iconfont icon-zuozhe"
                ><span>{{ item.author }}</span></i
              >
              <i class="iconfont icon-time"
                ><span>{{ formatDay(item.createdAt) }}</span></i
              >
            </div>
          </div>
        </li>
      </ul>
    </div>
    <Pagination :totalPages="totalPages" @pageChange="pageChange" />
  </div>
</template>

<script >
import {
  defineComponent,
  onMounted,
  ref,
  onBeforeMount,
  reactive,
  toRefs,
  watch,
  computed,
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { formatDay } from "../../libs/toolsLib";
import Pagination from "../../libs/WeisonUI/Pagination";
import http from "../../services/http";
import {
  getElementPosition,
  getItemNode,
  getViewportSize,
} from "../../libs/tools";
export default defineComponent({
  name: "ArticleList",
  components: { Pagination },
  setup() {
    const store = useStore();
    const storeState = store.state;
    const articleRef = ref(null);
    const titleRef = ref(null);
    const ulRef = ref(null);
    const router = useRouter();
    let articleList = null;
    const state = reactive({
      articles: [],
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      totalArticles: 0,
    });
    //请求文章列表数据
    const getArticles = async () => {
      const res = await http.get("articles", {
        params: state.queryInfo,
      });
      state.articles = res.data.articles;
      state.totalArticles = res.data.totalArticles;
    };
    onBeforeMount(() => {
      getArticles();
    });
    onMounted(() => {
      articleList = ulRef.value.children;
      bindEvent();
    });
    //点击卡片事件处理函数
    const bindEvent = () => {
      ulRef.value.addEventListener("click", (e) => {
        const tar = getItemNode(e.target);
        if (tar) {
          const index = [].indexOf.call(articleList, tar);
          router.push(`/article/${state.articles[index]._id}`);
        }

        // const { href } = router.resolve({
        //   path: `/article/${state.articles[index]._id}`,
        // });
        // window.open(href, "_blank");
      });
    };
    //监听滚动事件执行回调
    watch(
      () => {
        return storeState.scrolled.top;
      },
      (top) => {
        let viewportHeight = getViewportSize().height;
        let scrolled =
          (top - getElementPosition(titleRef.value).top + viewportHeight) /
          ulRef.value.offsetHeight;
        let total = 1 / articleList.length;
        //卡片逐行卷入效果
        for (let i = 0; i < articleList.length; i++) {
          let start = total * i,
            end = total * (i + 1);
          let process = (scrolled - start) / (end - start);
          process -= 0.4;
          if (process >= 1) {
            process = 1;
          }
          if (process < 0) {
            process = 0;
          }
          articleList[i].style.setProperty("--progress", process);
        }
      }
    );

    const totalPages = computed(() => {
      return Math.ceil(state.totalArticles / state.queryInfo.pageSize);
    });
    const pageChange = (newPage) => {
      state.queryInfo.pageNum = newPage;
      getArticles();
      titleRef.value.scrollIntoView({ behavior: "smooth" });
    };
    return {
      ...toRefs(state),
      articleRef,
      titleRef,
      ulRef,
      formatDay,
      pageChange,
      totalPages,
    };
  },
});
</script>
